package com.smartfast4j.backend.common.bean;

import com.alibaba.fastjson.JSON;
import com.smartfast4j.backend.common.util.AesEncryptUtils;
import com.smartfast4j.backend.common.util.RSAUtils;
import com.smartfast4j.backend.common.util.RandomUtils;

import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * 给客户端的返回数据
 *
 */
public class R extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;
	
	public R() {
		put("code", 0);
	}
	
	public static R error() {
		return error(500, "未知异常，请联系管理员");
	}
	
	public static R error(String msg) {
		return error(500, msg);
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.put("code", code);
		r.put("msg", msg);
		return r;
	}

	public static R ok(String msg) {
		R r = new R();
		r.put("msg", msg);
		return r;
	}
	
	public static R ok(Map<String, Object> map) {
		R r = new R();
		r.putAll(map);
		return r;
	}

	/**
	 * 将数据进行加密后返回
	 * @param map
	 * @return
	 */
	public static R okEncrypt(Map<String, Object> map) {
		//生成16位AES加密密钥
		String aesKey = RandomUtils.generateMixString(16);
		R r = new R();
		for(Entry<String,Object> entry : map.entrySet()){
			String key = entry.getKey();
			Object value = entry.getValue();
			try {
				//将返回数据进行AES加密
				String encryptData = AesEncryptUtils.aesEncrypt(JSON.toJSONString(value), aesKey);
				r.put(key, encryptData);
			} catch (Exception e) {
				r.put(key, value);
			}
		}
		r.put("aesKey", aesKey);
		//将aes加密密钥使用RSA进行加密，客户端再使用RSA解密
		//r.put("aesKey", RSAUtils.encryptString(aesKey));
		return r;
	}
	
	public static R ok() {
		return new R();
	}

	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	/**
	 * 将数据进行加密后返回
	 * @param key
	 * @param value
	 * @return
	 */
	public R putEncrypt(String key, Object value) {
		//生成16位AES加密密钥
		String aesKey = RandomUtils.generateMixString(16);
		try {
			//将返回数据进行AES加密
			String encryptData = AesEncryptUtils.aesEncrypt(JSON.toJSONString(value),aesKey);
			super.put(key, encryptData);
			super.put("aesKey", aesKey);
		} catch (Exception e) {
			super.put(key, value);
		}
		return this;
	}
}
